﻿using Edu.ZJ.Properties;

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Diagnostics;
using System.Drawing.Printing;

namespace Edu.ZJ
{
    public partial class MainForm : Form
    {
        private const string ABOUT_BLANK_URL = "about:blank";
        private const string DOWNLOAD_STRING = "[可以下载]:";

        private SiteModel site = SiteUtil.GetDefaultSite();
        private ExtChromiumBrowser webBrowser;
        private ToolTip toolTip;
        private int minWidth = 800;
        private int minHeight = 500;
        public MainForm()
        {
            InitializeComponent();

            InitBrowser();
            Init();
        }

        private void InitBrowser()
        {
            webBrowser = new ExtChromiumBrowser(site.HomeUrl)
            {
                Dock = DockStyle.Fill,
                MenuHandler = new ContextMenuHandler(),
                LifeSpanHandler = new CefLifeSpanHandler()
            };

            webBrowser.StartNewWindow += WebBrowser_StartNewWindow;
            webBrowser.FrameLoadEnd += WebBrowser_FrameLoadEnd;
            webBrowser.FrameLoadStart += WebBrowser_FrameLoadStart;

            if (site.NeedCookie)
            {
                string content = FileUtil.GetFileContent(site.Cookie.DirName, site.Cookie.FileName);
                if (!string.IsNullOrEmpty(content))
                {
                    var strs = content.Split('|');
                    if (strs.Length > 1)
                    {
                        if (DateTime.TryParse(strs[1], out DateTime dt))
                        {
                            SetCookie(site.Cookie.CookieName, strs[0], site.Cookie.Domain, dt);
                        }
                    }
                }
            }

            panel3.Controls.Add(webBrowser);
        }

        private void WebBrowser_FrameLoadStart(object sender, CefSharp.FrameLoadStartEventArgs e)
        {
            SetUrl(e.Url);
        }

        private void Init()
        {
            this.ResizeEnd += MainForm_ResizeEnd;
            backPic.Click += BackPic_Click;
            forwardPic.Click += ForwardPic_Click;
            refreshPic.Click += RefreshPic_Click;
            openFolderPic.Click += OpenFolderPic_Click;
            printPic.Click += PrintPic_Click;
            helpPic.Click += HelpPic_Click;
            picWebsite.Click += PicWebsite_Click;
            homePic.Click += HomePic_Click;
            picAccount.Click += PicAccount_Click;

            toolTip = new ToolTip();

            toolTip.SetToolTip(picAccount, "设置账号");
            toolTip.SetToolTip(picWebsite, "切换网站");
            toolTip.SetToolTip(backPic, "后退");
            toolTip.SetToolTip(forwardPic, "前进");
            toolTip.SetToolTip(homePic, "首页");
            toolTip.SetToolTip(refreshPic, "刷新");
            toolTip.SetToolTip(openFolderPic, "打开下载目录");
            toolTip.SetToolTip(downloadPic, "万能下载");
            toolTip.SetToolTip(printPic, "打印");
            toolTip.SetToolTip(helpPic, "帮助说明");
        }

        private void MainForm_ResizeEnd(object sender, EventArgs e)
        {
            if (this.Width < minWidth)
            {
                this.Width = minWidth;
            }

            if (this.Height < minHeight)
            {
                this.Height = minHeight;
            }
        }

        private void PicAccount_Click(object sender, EventArgs e)
        {
            AccountForm form = new AccountForm();
            if (form.ShowDialog() == DialogResult.OK)
            {
                var list = form.GetList();
                AccountUtil.Update(list);
            }
        }

        private void HomePic_Click(object sender, EventArgs e)
        {
            if (webBrowser != null)
            {
                webBrowser.Load(site.HomeUrl);
            }
        }

        private void PicWebsite_Click(object sender, EventArgs e)
        {
            SwitchSiteForm form = new SwitchSiteForm(site.Code);
            DialogResult result = form.ShowDialog();
            if (result == DialogResult.OK)
            {
                string code = form.SiteCode;
                if (string.IsNullOrEmpty(code) || code == site.Code)
                {
                    return;
                }

                site = SiteUtil.GetSiteByCode(code);

                if (webBrowser != null)
                {
                    webBrowser.LoadUrl(site.HomeUrl);
                }
            }
        }

        private void HelpPic_Click(object sender, EventArgs e)
        {
            HelpForm helpForm = new HelpForm();
            helpForm.ShowDialog();
        }

        private void PrintPic_Click(object sender, EventArgs e)
        {
            OpenFileDialog dlg = new OpenFileDialog();
            dlg.InitialDirectory = FileUtil.GetFilePath(site.Download.DirName);
            dlg.Title = "选择试卷";
            dlg.Filter = "PDF文档|*.pdf";
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                bool printFlag = false;
                try
                {
                    //PrintDocument doc = new PrintDocument();
                    //LogUtil.Instance.WriteLog($"打印机名称:{doc.PrinterSettings.PrinterName}");
                    //printFlag = PrintUtil.SendFileToPrinter(doc.PrinterSettings.PrinterName, dlg.FileName);

                    Process print = new Process();
                    //不现实调用程序窗口,但是对于某些应用无效
                    print.StartInfo.CreateNoWindow = true;
                    print.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                    //采用操作系统自动识别的模式
                    print.StartInfo.UseShellExecute = true;
                    //要打印的文件路径，可以是WORD,EXCEL,PDF,TXT等等
                    print.StartInfo.FileName = dlg.FileName;
                    //指定执行的动作，是打印，即print，打开是 open
                    print.StartInfo.Verb = "open";//开始
                    print.Start();
                    printFlag = true;
                }
                catch (Exception ex)
                {
                    LogUtil.Instance.Error("打印文件报错");
                    LogUtil.Instance.Error(ex);
                }
                if (!printFlag)
                {
                    MessageBox.Show("打印失败,请尝试手工打印!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                }
            }
        }

        private void OpenFolderPic_Click(object sender, EventArgs e)
        {
            try
            {
                string path = FileUtil.GetFilePath(site.Download.DirName);
                ProcessStartInfo processStartInfo = new ProcessStartInfo();
                processStartInfo.UseShellExecute = false;
                processStartInfo.CreateNoWindow = true;
                processStartInfo.FileName = "explorer.exe";
                processStartInfo.Arguments = path;

                Process.Start(processStartInfo);
            }
            catch(Exception ex)
            {
                LogUtil.Instance.Error(ex);
            }
        }

        private void RefreshPic_Click(object sender, EventArgs e)
        {
            string url = textUrl.Text;
            if (string.IsNullOrEmpty(url))
            {
                if (webBrowser != null)
                {
                    url = webBrowser.Address;
                }
            }
            else
            {
                url = url.Replace(DOWNLOAD_STRING, "");
            }

            if (string.IsNullOrEmpty(url))
            {
                url = site.HomeUrl;
            }

            if (webBrowser != null)
            {
                webBrowser.LoadUrl(url);
            }
        }

        private void ForwardPic_Click(object sender, EventArgs e)
        {
            if (webBrowser == null)
            {
                return;
            }

            if (webBrowser.CanGoForward)
            {
                webBrowser.GetBrowser().GoForward();
            }
        }

        private void BackPic_Click(object sender, EventArgs e)
        {
            if (webBrowser == null)
            {
                return;
            }

            if (webBrowser.CanGoBack)
            {
                webBrowser.GetBrowser().GoBack();
            }
        }

        private void WebBrowser_FrameLoadEnd(object sender, CefSharp.FrameLoadEndEventArgs e)
        {
            this.SetGoBack(webBrowser.CanGoBack);
            this.SetGoForward(webBrowser.CanGoForward);

            string url = e.Url;
            if (string.IsNullOrEmpty(url))
            {
                return;
            }

            CheckDownload(url);

            site.FrameLoadEnd?.Invoke(url, site, webBrowser);
        }

        private void WebBrowser_StartNewWindow(object sender, NewWindowEventArgs e)
        {
            webBrowser.Load(e.Url);

            SetUrl(e.Url);
        }

        private void SetCookie(string name, string value, string domain, DateTime expire)
        {
            var cookieManager = CefSharp.Cef.GetGlobalCookieManager();
            cookieManager.SetCookie(site.HomeUrl, new CefSharp.Cookie()
            {
                Domain = domain,
                Name = name,
                Value = value,
                Expires = expire
            });
        }

        private async void DownloadPic_Click(object sender, EventArgs e)
        {
            if (webBrowser == null)
            {
                return;
            }

            LoadingUtil.Show("正在下载...");

            string js = FileUtil.GetFileContent(site.Script.DirName, site.Script.FileName);
            var jsResponse = await webBrowser.EvaluateScriptAsync(js);
            if (jsResponse.Success)
            {
                var list = jsResponse.Result as List<object>;
                if (list != null && list.Count > 0)
                {
                    string html = list[0].ToString();
                    if (html == "none")
                    {
                        LoadingUtil.Close();
                        MessageBox.Show("暂无下载内容!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return;
                    }

                    string name = list[1].ToString();
                    if (string.IsNullOrEmpty(name))
                    {
                        name = DateTime.Now.ToString("yyyyMMddhhmmss");
                    }
                    else
                    {
                        name = $"{name}{DateTime.Now.ToString("HHmmss")}";
                    }

                    string content = FileUtil.GetFileContent(site.Html.DirName, site.Html.FileName);
                    content = content.Replace("#{content}", html);

                    string path = FileUtil.GetFilePath(site.Download.DirName, string.Format(site.Download.FileName, name));

                    //LogUtil.Instance.WriteLog(content);

                    HtmlToPdf toPdf = new HtmlToPdf(content);
                    toPdf.SaveFile(path);

                    LoadingUtil.Close();
                    MessageBox.Show("下载完毕!");
                }
            }
            else
            {
                MessageBox.Show(jsResponse.Message);
                LoadingUtil.Close();
            }
        }

        private async void CheckDownload(string url)
        {
            string js = FileUtil.GetFileContent(site.Script.DirName, site.Script.FileName);
            var jsResponse = await webBrowser.EvaluateScriptAsync(js);
            if (jsResponse.Success)
            {
                var list = jsResponse.Result as List<object>;
                if (list != null && list.Count > 0)
                {
                    string html = list[0].ToString();
                    if (!string.IsNullOrEmpty(html) && html != "none")
                    {
                        SetUrl(DOWNLOAD_STRING + url, true);
                        return;
                    }
                }
            }

            SetUrl(url);
        }

        private void SetGoBack(bool flag)
        {
            this.Invoke(new Action(() =>
            {
                if (flag)
                {
                    backPic.Image = Resources.back1;
                    backPic.Enabled = true;
                }
                else
                {
                    backPic.Image = Resources.back2;
                    backPic.Enabled = false;
                }
            }));
        }

        private void SetGoForward(bool flag)
        {
            this.Invoke(new Action(() =>
            {
                if (flag)
                {
                    forwardPic.Image = Resources.forward1;
                    forwardPic.Enabled = true;
                }
                else
                {
                    forwardPic.Image = Resources.forward2;
                    forwardPic.Enabled = false;
                }
            }));
        }

        private void SetUrl(string url, bool flag = false)
        {
            this.Invoke(new Action(() =>
            {
                if (url != ABOUT_BLANK_URL)
                {
                    textUrl.Text = url;
                    if (flag)
                    {
                        textUrl.ForeColor = System.Drawing.Color.Green;
                    }
                    else
                    {
                        textUrl.ForeColor = System.Drawing.Color.Black;
                    }
                }
            }));
        }
    }
}
